package com.example.testanything;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.http.util.ByteArrayBuffer;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.testanything.LongToString;
public class MainActivity extends Activity {
	private Button bt;
	private ProgressBar progressbar;
	private TextView dis,talking;
	int count = 0;
	
	private IINN th2;
	private int Statue = 0;
	private ImageView picture ;
	private int sign_p = 0;
	private LongToString TURN ;
	Thread bar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dis = (TextView)findViewById(R.id.textView1);
        talking = (TextView)findViewById(R.id.getInfo);
        bt= (Button)findViewById(R.id.bt);
        picture = (ImageView)findViewById(R.id.picture0);
        
      //  th1 =  new  my_th();
        th2 = new IINN();
        progressbar = (ProgressBar) findViewById(R.id.process_bar);
        bt.setOnClickListener(new OnClickListener (){

			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub		
				progressbar.setVisibility(ProgressBar.VISIBLE);
				my_th th1 = new my_th();
				if (Statue == 0){
					
					th1.start();
					th2.start();
					Statue = 1;
				}else if (th2.isAlive() && Statue ==1){
					
				}
				
				if (progressbar.getProgress() > 90){
	    			Toast.makeText(getApplicationContext(),String.valueOf(Thread.activeCount()), Toast.LENGTH_SHORT).show();
	    	
	    		}
				
			}
        	
        });
        //Toast.makeText(getApplicationContext(), String.valueOf(Thread.activeCount()), Toast.LENGTH_SHORT).show();
    }


    Handler handler = new  Handler(){
    	@Override
    	public void handleMessage(Message msg){
    		//super.sendMessage(msg);
    		
	    		progressbar.setProgress(msg.arg1);
	    		if (progressbar.getProgress() > 98){
	    			Toast.makeText(getApplicationContext(),Thread.currentThread().getName(), Toast.LENGTH_SHORT).show();
	    			
	    		}
    		if (msg.what == 1){
    			Toast.makeText(getApplicationContext(), "end or ??" +String.valueOf(Thread.activeCount()),Toast.LENGTH_SHORT).show();
    			count = 0;
    		}
    		if (msg.obj != null && msg.what != 999){
    			
    			Toast.makeText(getApplicationContext(), String.valueOf(msg.arg2), Toast.LENGTH_SHORT).show();
    			talking.setText((String)msg.obj);
    		}
    		if (msg.what == 999 ){
    			talking.setText("get picture...");
    			Bundle bundle = msg.getData();
    			byte[] buf = bundle.getByteArray("picture");
    			
    			Bitmap bitmap  = BitmapFactory.decodeByteArray(buf, 0, buf.length);
    			if (bitmap != null){
    				talking.setText("get picture ... ok");
    				picture.setImageBitmap(bitmap);
    			}
    		}
    		
    	}
    };
    class my_th extends Thread{

		@SuppressWarnings("deprecation")
		@Override
		public void run() {
			// TODO Auto-generated method stub
			
			int sign = 0;
			
				
			while (count < 100){
				Message msg = new Message();
				count += 1;
				try{
					Thread.sleep(50);
				}catch (InterruptedException e){
					e.printStackTrace();
				}
				msg.arg1 = count;
			
				MainActivity.this.handler.sendMessage(msg);
				Log.d("now thread",String.valueOf(Thread.activeCount()));
				
			}
			if (count == 100){
				MainActivity.this.handler.removeCallbacks(this);
				Message msg = new Message();
				msg.what = 1;
			}


			
			
		}
    	
    };
    class IINN extends Thread {
    	@SuppressWarnings("resource")
		@Override
		public void run() {
    		Socket client ;
    		
    		while (true){
    			client = new Socket();
    			boolean DOWNLOADED = false; //
    			byte[] header = new byte[12];
    			byte[] body = null;
    			Bitmap bitmap ;
    			SocketAddress remote  = new InetSocketAddress("192.168.1.100",50000);
			
				try {
					client.connect(remote);
				} catch (ConnectException e){
					Message msg_E = new Message();
					String error = e.toString();
					msg_E.obj = (Object)error;
					handler.sendMessage(msg_E);
					break;
				}catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					break;
				}catch (IOException e){
					e.printStackTrace();
				}
				if (!client.isConnected()){
					continue;
				}
			
				InputStream IS = null;
				try {
					IS = client.getInputStream();
					Log.d("ContentSSS", String.valueOf(IS.available()));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				int FILE_LEN = 0 ;
				try {
					IS.read(header, 0,4);
					String head = new String(header,0,4,"utf-8"); //非常需要注意。。。。
					Log.d("ContentType",head);
					if (head.equals("pict")){
						
						sign_p =1 ;
					}
					IS.read(header,4,8);
					
					String FILE_LEN_s = new String(header,"utf-8");
					TURN = new LongToString(FILE_LEN_s);
					FILE_LEN = (int)TURN.getInteger();
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				byte[] buf_content = new byte[FILE_LEN];
				//Log.d("HEADER_LEN",String.valueOf());
				Log.d("FILE_LEN",String.valueOf(FILE_LEN));
				
				//int readable_int = 0;  //确认可读文件的大小
				//try {
					//readable_int = IS.available();
				//} catch (IOException e2) {
					/// TODO Auto-generated catch block
					//e2.printStackTrace();
			//	} //
				
				/*
				 * 首次传送文件
				 */
				try {
					if(FILE_LEN == 0){
						continue;
					}
					Log.d("FILE_LEN","Content len:"+String.valueOf(IS.available()));
					int remain_byte = FILE_LEN; //assure file's remain length .from header.
					int start_byte = 0;
					int readable_int = 1;
					while (remain_byte > 0){   //because progress may not read all ..
						IS.read(buf_content,start_byte,readable_int);
						//readable_int = IS.available() ;//care of !!!
						
						start_byte += readable_int ;   //start position 
						remain_byte -= readable_int;
					}
					if (remain_byte == 0){
						DOWNLOADED = true;
						OutputStream OS = client.getOutputStream();
						String end = "END";
						byte[] end_bytes = end.getBytes("utf-8");
						OS.write(end_bytes);
						OS.flush();
					}
					try {
						Log.d("FILE_LEN","Content len (old):"+String.valueOf(IS.available()));
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				/*
				 * 丢失文件处接着传
				 */
				try {
					/*
					 * 断点续传
					 */
					/*
					while (DOWNLOADED  != true){
						OutputStream OS = client.getOutputStream();
						byte[] cut_point_position = String.valueOf(readable_int).getBytes();
						OS.write(cut_point_position);
						OS.flush();
						InputStream CIS = client.getInputStream();
					}
					*/
					Log.d("FILE_LEN","Content len(old):"+String.valueOf(IS.available()));
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				String SAY = null;
				if (sign_p == 0){
					try {
						SAY =  new String(buf_content,"utf-8");
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					Log.d("ContentSSS",SAY);	
					Message msg = new Message();
					msg.obj = (Object) SAY;
					msg.arg2 = sign_p;
					handler.sendMessage(msg);
				}else if (sign_p == 1){

					Message msg_p = new Message();
					msg_p.what = 999; //this represent picture;
					Bundle P_data = new Bundle();
					P_data.putByteArray("picture", buf_content);
					msg_p.setData(P_data);
					handler.sendMessage(msg_p);
					sign_p = 0;
				}	
				
    		}
    		
    	}
    }
    public void test(View view){
    	Date date = new Date(System.currentTimeMillis());
    	SimpleDateFormat formater = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    	String time  = formater.format(date);
    	dis.setText(time);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}
